package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 03-Cookie基本使用
 * ②获取浏览器发送过来的cookie
 */
@WebServlet("/demo02")
public class Demo02Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取浏览器发送过来的Cookie，通过请求头Cookie来获取
        Cookie[] cookies = req.getCookies();
        Cookie myCookie = null;
        if (null == cookies || 0 == cookies.length) {

        } else {
            for (Cookie cookie : cookies) {
                if ("msg".equals(cookie.getName())) {
                    myCookie = cookie;
                }
            }
        }

        if (null == myCookie) {
            System.out.println("没有找到cookie");
        } else {
            System.out.println("name = " + myCookie.getName() + " , value = " + myCookie.getValue());
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
